#include "DelayedActionServiceImpl.h"

ARELLO_GAME_NAMESPACE_DECL_START

DelayedActionServiceImpl::DelayedActionServiceImpl()
{
}

DelayedActionServiceImpl::~DelayedActionServiceImpl()
{
}

void DelayedActionServiceImpl::Schedule(boost::function<void ()> action)
{
	ScheduleDeferred(static_cast<time_float>(0.0), action);
}

void DelayedActionServiceImpl::ScheduleDeferred(time_float delay, boost::function<void ()> action)
{
	delayedActions.push_back(std::make_pair(delay, action));
}

void DelayedActionServiceImpl::Perform(time_float dt)
{
	for (DelayedActionsVector::iterator i = delayedActions.begin(); i != delayedActions.end(); ++i)
		i->first -= dt;

	DelayedActionsVector notYet;

	while (!delayedActions.empty())
	{
		std::pair<time_float, boost::function<void ()> > p = delayedActions.back();
		delayedActions.pop_back();
		if (p.first <= 0)
			p.second();
		else
			notYet.push_back(p);
		
	}

	delayedActions = notYet;
}

ARELLO_GAME_NAMESPACE_DECL_END